<template>
  <div>
    <el-dialog
      title="导入"
      :visible.sync="dialogVisible"
      width="30%">
      <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="submitImport">确 定</el-button>
    </span>
      <el-upload
        class="upload-demo"
        drag
        action="#"
        accept=".xls, .xlsx"
        :auto-upload="false"
        :file-list="fileList"
        :on-change="handleChange"
        multiple>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">只能上传单个.xls,.xlsx文件，且不超过10MB</div>
      </el-upload>
    </el-dialog>
  </div>
</template>
<script>

import {importOrder} from "@/api/warehouse/inbuond"
import * as XLSX from 'xlsx/xlsx.mjs'

export default {
  name: "DataImport",
  data(){
    return{
      loading:false,
      dialogVisible:false,
      file:null,
      uploadRef: null,
      fileList:[],
      uploadUrl:"",
      submitData:[],
  }
  },
  methods:{
    reset(){
      this.loading=false
      this.dialogVisible=false
      this.file=null
      this.uploadRef=null
      this.fileList=[]
      this.uploadUrl=""
      this.submitData=[]
    },
    /**( 导入按钮操作 */
    submitImport(){
      const reader = new FileReader();
      reader.onload = (e) => {
        console.log(e)
        try {
          const data = new Uint8Array(e.target.result);
          const workbook = XLSX.read(data, { type: 'array' });
          const firstSheetName = workbook.SheetNames[0];
          const worksheet = workbook.Sheets[firstSheetName];
          // 转换为JSON数据
          // 工作表有3行表头，包含合并单元格
          //第一列为序号，serialNumber不存入数据库中，
          this.submitData = XLSX.utils.sheet_to_json(worksheet,{
            raw:true,
            header:[
              "serialNumber",
              "sampleNo",
              "surveyShip",
              "voyage",
              "marineArea",
              "position",
              "xCoordinate",
              "yCoordinate",
              "detailAddress",
              "endDepth",
              "heartLong",
              "storageLocation",
              "preservationStatus",
              "remark",
            ],
            range:3,
            defval:null
          });
          importOrder(this.submitData).then(res => {
            console.log(res)
            if (res.code === 200){
              this.$message({
                showClose: true,
                message: '导入成功',
                type: 'success'
              });
              this.$emit('search')
                this.dialogVisible = false;
            }
            console.log(res)
          })
        } catch (error) {
          this.$message.error('解析Excel文件失败，请检查文件格式');
          console.error(error);
        }
      };

      reader.readAsArrayBuffer(this.file.raw);
    },
    // 处理文件变化
    handleChange(uploadFile,fileList) {
      //保证多选时，以最后一个为准
      if (fileList.length>0){
        this.fileList = [fileList[fileList.length - 1]]
      }
      const isXLSX = uploadFile.name.endsWith('.xlsx');
      const isXLS = uploadFile.name.endsWith('.xls')
      console.log(isXLSX)
      console.log(isXLS)
      const isLt10M = uploadFile.size / 1024 / 1024 < 10;

      if (!(isXLSX || isXLS)) {
        this.$message.error('上传文件格式必须为.xlsx或者.xls');
        // 过滤掉非法文件
          this.fileList= fileList.filter(f => f.uid !== uploadFile.uid);
        return;
      }
      if (!isLt10M) {
        // 过滤掉非法文件
        this.fileList = fileList.filter(f => f.uid !== uploadFile.uid);
        this.$message.error('上传文件大小不能超过10MB!');
        return;
      }
      this.file = uploadFile;
    },

    // 取消上传
    cancelUpload() {
      this.file = null;
      this.uploadRef.clearFiles();
      this.submitData = [];
    },

    // 文件验证
    beforeUpload(uploadFile) {

    },
  }
}
</script>
<style scoped lang="scss">

</style>
